/*
 * @Description:
 * @Author: zheng yiliang
 * @Date: 2021-04-18 19:04:47
 * @LastEditTime: 2021-06-13 17:32:06
 * @LastEditors: zheng yiliang
 */
var express = require('express');
var router = express.Router();
const mongoose = require('../core/mongodb');
const { SuccessModel, ErrorModel } = require('../util');
const { Article, Comment } = require('../model');
const loginCheck = require('../middleware/loginCheck');
const { upload } = require('../util/upload');
const { BASE_URL } = require('../core/constant');
// let OSS = require('ali-oss');

// let client = new OSS({
//   region: '<Your region>',
//   accessKeyId: '<Your AccessKeyId>',
//   accessKeySecret: '<Your AccessKeySecret>',
//   bucket: '<Your bucket name>'
// });

// async function putBuffer () {
//   try {
//     let result = await client.put('object-name', new Buffer('hello world'));
//     console.log(result);
//   } catch (e) {
//     console.log(e);
//   }
// }
router.post('/add', loginCheck, upload.single('articleImg'), async (req, res) => {
  const { title, author, secret, top, keyword, content, desc, tags, category, state, type, origin } = req.body
  let url = ''
  if (req.file) {
    url = `${BASE_URL}/${req.file.path}`
  } else {
    url = `${BASE_URL}/static/article/default.png`
  }
  const tempArticle = new Article({
    secret: secret * 1,
    title,
    author,
    keyword: keyword || [],
    content,
    numbers: content.length,
    desc,
    top: top * 1 || 0,
    img_url: url,
    tags: tags ? tags.split(',') : [],
    category: category || [],
    state: state * 1,
    type: type * 1,
    origin: origin * 1
  })
  tempArticle
    .save()
    .then(data => {
      console.log(state)
      if (state * 1) return res.json(new SuccessModel('创建文章成功'))
      return res.json(new SuccessModel('已存入草稿箱'))
    })
    .catch(err => {
      console.log(err)
      res.json(new ErrorModel('文章创建失败，请联系管理员'))
      // responseClient(res);
    });
})

router.get('/all', loginCheck, (req, res) => {
  const { pagenum, pagesize, keyword, secret, dateRange, origin, type, category, state, likes } = req.query
  const pageNum = pagenum * 1 || 1
  const pageSize = pagesize * 1 || 5
  let conditions = {}
  if (keyword) {
    const reg = new RegExp(keyword, 'i')
    conditions = {
      $or: [{ title: { $regex: eval(reg) } }, { desc: { $regex: eval(reg) } }]
    }
  }
  if (origin) conditions.origin = origin * 1
  if (secret) conditions.secret = secret * 1
  if (state) conditions.state = state * 1
  if (type) conditions.type = type * 1
  if (category) conditions.category = category
  if (dateRange) conditions.create_time = {
    "$gte": new Date(`${dateRange[0]} 00:00:00`),
    "$lte": new Date(`${dateRange[1]} 23:59:59`)
  }

  let skip = pageNum - 1 < 0 ? 0 : (pageNum - 1) * pageSize;
  let responseData = {
    count: 0,
    list: [],
  };
  Article.countDocuments(conditions, (err, count) => {
    if (err) {
      console.log('Error:' + err);
    } else {
      responseData.count = count;
      // 待返回的字段
      let fields = {
        title: 1,
        author: 1,
        keyword: 1,
        top: 1,
        // content: 1,
        desc: 1,
        img_url: 1,
        tags: 1,
        category: 1,
        state: 1,
        type: 1,
        origin: 1,
        comments: 1,
        like_User_id: 1,
        meta: 1,
        create_time: 1,
        secret: 1
        // update_time: 1,
      };
      let options = {
        skip: skip,
        limit: pageSize,
        sort: { create_time: -1 },
      }
      Article.find(conditions, fields, options)
        .populate([
          { path: 'tags' },
          { path: 'comments' },
          { path: 'category' }
        ])
        .exec((err, doc) => {
          if (err) {
            console.error('Error:' + err)
            // throw error;
          } else {
            if (likes) {
              doc.sort((a, b) => {
                return b.meta.likes - a.meta.likes
              });
            }
            responseData.list = doc;
            return res.json(new SuccessModel(responseData, '文章列表获取成功'))

            // responseClient(res, 200, 0, '操作成功！', responseData)
          }

          // console.log("doc:");          // aikin
          // console.log("doc.tags:",doc.tags);          // aikin
          // console.log("doc.category:",doc.category);           // undefined
        })
    }
  })
})

router.get('/detail', loginCheck, (req, res) => {
  const { id } = req.query
  // 待返回的字段
  let fields = {
    title: 1,
    author: 1,
    keyword: 1,
    // content: 1,
    desc: 1,
    img_url: 1,
    tags: 1,
    category: 1,
    state: 1,
    type: 1,
    origin: 1,
    comments: 1,
    content: 1,
    secret: 1,
    top: 1,
    // like_User_id: 1,
    // meta: 1,
    create_time: 1
    // update_time: 1,
  };
  Article.findById(id, fields).populate([
    { path: 'tags' },
    // { path: 'comments' },
    { path: 'category' }
  ])
    .exec((err, doc) => {
      if (err) {
        console.error('Error:' + err)
        // throw error;
      } else {
        return res.json(new SuccessModel(doc, '文章列详情取成功'))

        // responseClient(res, 200, 0, '操作成功！', responseData)
      }

      // console.log("doc:");          // aikin
      // console.log("doc.tags:",doc.tags);          // aikin
      // console.log("doc.category:",doc.category);           // undefined
    })
})

router.put('/edit', loginCheck, upload.single('articleImg'), (req, res) => {
  const {
    title,
    author,
    articleImg,
    keyword,
    content,
    desc,
    img_url,
    tags,
    category,
    state,
    secret,
    type,
    origin,
    top,
    _id } = req.body
  let url = ''
  console.log(req.body, req.params, req.query)
  // if (articleImg) {
  //   upload.single('articleImg')
  // }
  if (req.file) {
    url = `${BASE_URL}/${req.file.path}`
  } else if (img_url) {
    url = img_url
  } else {
    url = `${BASE_URL}/static/article/default.png`
  }
  Article.findByIdAndUpdate(_id,
    {
      secret: secret * 1,
      title,
      author,
      keyword: keyword || [],
      content,
      numbers: content.length,
      desc,
      top,
      img_url: url,
      tags: tags ? tags.split(',') : [],
      category: category || [],
      state: state * 1,
      type: type * 1,
      origin: origin * 1,
      update_time: Date.now()
    },
  )
    .then(result => {
      return res.json(new SuccessModel('修改成功'))
    })
    .catch(err => {
      return res.json(new ErrorModel('修改失败'))
    });
})

router.delete('/del', loginCheck, (req, res) => {
  const { id } = req.body;
  Article.findByIdAndDelete(id).then(result => {
    return res.json(new SuccessModel('删除成功'))
    // if (result.n === 1) {
    //   responseClient(res, 200, 0, '删除成功!');
    // } else {
    //   responseClient(res, 200, 1, '文章不存在');
    // }
  }).catch(err => {
    return res.json(new ErrorModel('删除失败'))
    // console.error('err :', err);
    // responseClient(res);
  });
})

router.get('/commentsByArticle', loginCheck, (req, res) => {
  const { article_id } = req.query
  Comment.aggregate([
    {
      $lookup: {
        from: "webusers",
        localField: "user_id",
        foreignField: "user_id",
        as: "user"
      }
    },
    {
      $sort: { create_time: -1 }
    },
    {
      $match: { article_id: mongoose.Types.ObjectId(article_id) }
    }
  ], function (err, docs) {
    if (err) return res.json(new ErrorModel(PUBLIC_ERROR_MSG))
    const comments = docs.map(item => {
      return {
        name: item.user[0].name,
        id: item.user_id,
        article_id: item.article_id,
        headImg: item.user[0].avatar,
        comment: item.comment,
        time: item.create_time,
        like: item.likes,
        inputShow: false,
        _id: item._id,
        is_handle: item.is_handle,
        type: item.user[0].type,
        reply: item.reply.map(ele => {
          return {
            ...ele,
            inputShow: false
          }
        })
      }
    })
    return res.json(new SuccessModel(comments, '评论列表获取成功'))
  })
})

router.post('/replyComments', loginCheck, (req, res) => {
  const item = {
    from: req.body.from,
    fromId: req.cookies.openid,
    fromAvatar: req.body.fromAvatar,
    fromType: 0,
    to: req.body.to,
    toId: req.body.toId,
    toType: req.cookies.openid === '1099AFF3DD0136F3B4E77B303E40C4E2' ? 0 : 1,
    toAvatar: req.body.toAvatar,
    comment: req.body.comment,
    // id: new mongoose.Types.ObjectId(),
    is_handle: 1
  }
  Comment.findByIdAndUpdate(req.body._id, {
    $addToSet: {
      reply: item
    }
  }).then(data => {
    console.log(data)
    return res.json(new SuccessModel(data, '回复评论成功'))
    console.log('回复评论成功')
  }).catch(err => {
    // return res.json(new ErrorModel(PUBLIC_ERROR_MSG))
    console.log(err)
  })
})

router.delete('/delReplyComment', loginCheck, (req, res) => {
  const { replyId } = req.body
  console.log(req.body)
  Comment.findByIdAndUpdate(req.body._id, {
    $pull: {
      reply: { _id: replyId }
    }
  }).then(data => {
    return res.json(new SuccessModel(data, '删除此评论成功'))
  }).catch(err => {
    console.log(err)
    return res.json(new ErrorModel(PUBLIC_ERROR_MSG))
  })
})

router.delete('/delComment', loginCheck, (req, res) => {
  const { id, article_id } = req.body;
  Comment.findByIdAndDelete(id).then(result => {
    Article.findById(article_id, { meta: 1 }).then(article => {
      article.meta.comments = article.meta.comments - 1;
      Article.findByIdAndUpdate(article_id, { meta: article.meta })
        .then(result => {
          return res.json(new SuccessModel('删除成功'))
        })
    })
  }).catch(err => {
    return res.json(new ErrorModel('删除失败'))
  });
})

router.put('/read', loginCheck, (req, res) => {
  Comment.findByIdAndUpdate(req.body._id, {
    is_handle: 1
  }
  ).then(data => {
    return res.json(new SuccessModel('成功标记为已读'))
  }).catch(err => {
    return res.json(new ErrorModel('标记为已读失败'))

  })
})

router.put('/replyRead', loginCheck, (req, res) => {
  console.log(req.body)
  Comment.updateOne({ _id: req.body._id, 'reply._id': req.body.replyId }, {
    $set: { "reply.$.is_handle": 1 }
  }).then(data => {
    if (data.nModified) {
      return res.json(new SuccessModel('成功标记为已读'))
    }
    return res.json(new ErrorModel('标记为已读失败'))
  }).catch(err => {

  })
})

router.put('/allRead', loginCheck, (req, res) => {
  console.log('多对多', req.body)
  Comment.updateMany({ article_id: req.body.article_id }, {
    $set: { "reply.$[].is_handle": 1 },
    is_handle: 1
  }).then(data => {
    console.log(data)
    if (data.nModified) {
      return res.json(new SuccessModel('成功一键标记为已读'))
    }
    return res.json(new ErrorModel('一键标记为已读失败'))
  }).catch(err => {

  })
})

module.exports = router;

